<template>
  <div class="formTable">
    <hot-table
      :readOnly="readOnly"
      class="hot_table"
      ref="hotTableComponent"
      :data="formData"
      :settings="hotSettings"
    ></hot-table>
  </div>
</template>

<script>
import { HotTable } from '@handsontable/vue'
import 'handsontable/dist/handsontable.full.css'
import 'handsontable/languages/zh-CN'
import { HyperFormula } from 'hyperformula'
export default {
  components: { HotTable },
  data() {
    return {
      total: 0
    }
  },
  props: {
    formData: {
      type: Array,
      default: () => []
    },
    attributes: {
      type: Object,
      default: () => ({
        numberType: 0,
        scoreRequire: 1,
        type: 0,
        maxlength: 300,
        scoreDesReq: 0
      })
    },
    cell: {
      type: Array,
      default: () => []
    },
    readOnly: {
      type: Boolean,
      default: false
    },
    isShared: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    hotSettings() {
      const unShareColumns = [
        {
          data: 'indicatorName',
          readOnly: true,
          headerClassName: 'header',
          width: 30
          // className: 'readOnly'
        },
        // {
        //   data: 'indicatorLevel',
        //   readOnly: true,
        //   headerClassName: 'header',
        //   // className: 'readOnly'
        // },
        {
          data: 'indicatorDes',
          readOnly: true,
          headerClassName: 'header',
          className: 'htLeft htMiddle'
        },
        {
          data: 'weight',
          readOnly: true,
          width: 20,
          headerClassName: 'header'
        },
        {
          data: 'scoreValue',
          type: 'numeric',
          headerClassName: 'header',
          width: 20,
          // allowEmpty: !(this.attributes?.scoreRequire),
          // validator: customValidator
          numericFormat: {
            pattern: this.attributes?.numberType === 0 ? '0a' : this.attributes?.numberType === 1 ? '0.0' : '0.00'
          },
          validator: (value, callback) => {
            if (this.attributes?.scoreRequire && (value === null || value === undefined || value === '')) {
              callback(false)
            } else if (value < 0 || value > 100) {
              callback(false)
            } else {
              callback(true)
            }
          }
        },
        // 评分说明
        {
          data: 'scoreDes',
          headerClassName: 'header',
          className: 'htLeft htMiddle',
          height: 20,
          // allowEmpty: !(this.attributes?.scoreRequire), // 不生效，不知道为啥
          validator: (value, callback) => {
            // 检查输入值的长度
            if (value.length > this.attributes?.maxlength) {
              // 如果长度超过最大长度
              callback(false, `最大长度为${this.attributes.maxlength}个字符`)
            } else if (this.attributes?.scoreDesReq && !value) {
              callback(false)
            } else {
              callback(true)
            }
          }
        },
        {
          data: 'totalScore',
          readOnly: true,
          headerClassName: 'header',
          width: 20,
          type: 'numeric',
          numericFormat: {
            pattern: this.attributes?.numberType === 0 ? '0a' : this.attributes?.numberType === 1 ? '0.0' : '0.00'
            // pattern: {
            //   trimMantissa: true,
            //   mantissa: this.attributes?.numberType
            // }
          }
        }
      ]

      const shareColumns = [
        {
          data: 'isActive',
          type: 'checkbox',
          readOnly: true,
          width: 20,
          checkbox: {
            checkedTemplate: true,
            uncheckedTemplate: false
          }
        },
        {
          data: 'indicatorName',
          readOnly: true,
          headerClassName: 'header',
          width: 30
          // className: 'readOnly'
        },
        // {
        //   data: 'indicatorLevel',
        //   readOnly: true,
        //   headerClassName: 'header',
        //   // className: 'readOnly'
        // },
        {
          data: 'indicatorDes',
          readOnly: true,
          headerClassName: 'header'
        },
        {
          data: 'weight',
          readOnly: true,
          width: 20,
          headerClassName: 'header'
        },
        {
          data: 'scoreValue',
          type: 'numeric',
          width: 20,
          headerClassName: 'header',
          // allowEmpty: !(this.attributes?.scoreRequire),
          // validator: customValidator
          numericFormat: {
            pattern: this.attributes?.numberType === 0 ? '0a' : this.attributes?.numberType === 1 ? '0.0' : '0.00'
            // pattern: {
            //   trimMantissa: true,
            //   mantissa: this.attributes?.numberType
            // }
          },
          validator: (value, callback) => {
            if (this.attributes?.scoreRequire && !value && !this.isShared && value != 0) {
              callback(false)
            } else if (value < 0 || value > 100) {
              callback(false)
            } else {
              callback(true)
            }
          }
        },
        // 评分说明
        {
          data: 'scoreDes',
          headerClassName: 'header',
          // allowEmpty: !(this.attributes?.scoreRequire), // 不生效，不知道为啥
          validator: (value, callback) => {
            // 检查输入值的长度
            if (value.length > this.attributes?.maxlength) {
              // 如果长度超过最大长度
              callback(false, `最大长度为${this.attributes.maxlength}个字符`)
            } else if (this.attributes?.scoreDesReq && !value) {
              callback(false)
            } else {
              callback(true)
            }
          }
        },
        {
          data: 'totalScore',
          readOnly: true,
          headerClassName: 'header',
          width: 20,
          type: 'numeric',
          numericFormat: {
            pattern: this.attributes?.numberType === 0 ? '0a' : this.attributes?.numberType === 1 ? '0.0' : '0.00'
            // pattern: {
            //   trimMantissa: true,
            //   mantissa: this.attributes?.numberType
            // }
          }
        }
      ]
      return {
        colHeaders: this.isShared
          ? [
              '是否评分',
              '评分指标',
              // "指标级别",
              '指标说明',
              '权重',
              '评分',
              '评分说明',
              '小计'
            ]
          : [
              '评分指标',
              // "指标级别",
              '指标说明',
              '权重',
              '评分',
              '评分说明',
              '小计'
            ],
        columns: this.isShared ? shareColumns : unShareColumns,
        // 给行添加样式
        cells: (row, col) => {
          const indTipCol = this.isShared ? 2 : 1
          const rateTipCol = this.isShared ? 5 : 4
          if (this.cell.some(item => item.row === row)) {
            return {
              className: col == indTipCol || col == rateTipCol ? 'readOnlyRow columnLeft' : 'readOnlyRow',
              readOnly: true,
              allowInvalid: true
            }
          }
        },
        beforeValidate: (value, row, col) => {
          if (this.cell.some(item => item.row == row && item.col == col)) {
            return true
          }
        },
        rowHeaders: true,
        // readOnlyCellClassName: 'red',
        // width: '100%',
        height: 'auto',
        colWidths: 50,
        rowHeights: 40,
        //自动拉伸
        stretchH: 'all',
        AutoColumnSize: true, // 自动调整列宽以适应最长文本
        language: 'zh-CN',
        //许可证
        licenseKey: 'ab3e4-1bee8-ed01c-4d94b-08cfe',
        className: 'htCenter htMiddle',
        filters: true, // 启用基本的筛选功能
        formulas: {
          engine: HyperFormula
        }, // 启用公式功能
        afterFormulasValuesUpdate: this.afterFormulasValuesUpdate,
        // updateData: this.updateData,
        // contextMenu: true, // 右键菜单
        manualRowResize: true,
        manualColumnResize: true,
        manualColumnMove: true,
        manualRowMove: true,
        autoWrapRow: true,
        autoWrapCol: true
      }
    }
  },
  watch: {
    formData: {
      handler() {
        this.$nextTick(() => {
          this.handleTotal()
        })
      },
      immediate: true
    }
  },
  methods: {
    afterFormulasValuesUpdate(changes) {
      // 评分这列发生变化
      if ((changes[0].address.col === 3 || changes[0].address.col === 4) && typeof changes[0].newValue === 'number') {
        this.$set(this.formData[changes[0].address.row], 'isActive', true)
        console.log('result', this.formData)
        this.handleTotal()
      } else {
        this.$set(this.formData[changes[0].address.row], 'isActive', false)
      }
    },

    handleTotal() {
      const result = this.$refs.hotTableComponent.hotInstance.getData()
      const sum = result.reduce((accumulator, row, index) => {
        if (this.formData[index]['indicatorLevel'] === '1级') {
          return accumulator + row[row.length - 1]
        }
        return accumulator
      }, 0)
      this.total = sum
      this.$emit('setTotal', this.total)
      return sum
    }
  }
}
</script>

<style lang="less" scoped>
// 只读单元格样式
/deep/.hot_table {
  .handsontable {
    font-size: 16px;
    // color: #000;
    // font-weight: 600;
    th {
      vertical-align: middle;
    }
    .htDimmed {
      color: #373737;
      // background: #eee;
    }
  }
  .header {
    height: 40px;
    line-height: 40px;
  }
  .readOnlyRow {
    background-color: #f0f0f0;
    vertical-align: middle;
    text-align: center;
    &:hover {
      cursor: not-allowed;
    }
  }
  .columnLeft {
    text-align: left;
  }
}
</style>
